package data.communication.lab1;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ServerClient {

	private static final int PORT = 8000;
	private static final String SERVER = "194.47.32.226";

	public static void main(String[] args) {
		new ServerClient(SERVER, PORT);
	}

	public ServerClient(String server, int port) {
		BufferedReader inputFromServer;
		PrintStream outputToServer;
		try {
			System.out.println("Connecting");
			try (Socket socket = new Socket(server, port)) {
				System.out.println("Connection established!");

				Scanner sc = new Scanner(System.in);

				outputToServer = new PrintStream(socket.getOutputStream());
				inputFromServer = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				while (true) {
					System.out.println("Enter command: ");
					String getString = sc.nextLine();

					if (getString.equals("exit")) {
						break;
					}

					outputToServer.print(getString);
					outputToServer.flush();

					String output = inputFromServer.readLine();
					System.out.println("received: " + output);

					if (getString.length() > 2) {
						if (getString.substring(0, 3).equals("get")) {

							int byteSize = Integer.parseInt(output);
							System.out.println("Number of bytes: " + byteSize);

							if (byteSize > 0) {
								byte[] buffer = new byte[1000];
								System.out.println("Downloading file...");

								BufferedInputStream fileInput = new BufferedInputStream(
										socket.getInputStream());

								File outputFile = new File(
										"/Applications/Android development/workspace/DataCommunicationLab1/dwl/"
												+ getString.substring(4,
														getString.length()));

								if (!outputFile.exists()) {
									outputFile.createNewFile();
								}

								FileOutputStream fileOutputStream = new FileOutputStream(
										outputFile);

								int remainder = byteSize;
								int sent = 0;
								while (remainder > 0) {
									sent = fileInput.read(buffer);
									remainder -= sent;
									if (sent > 0) {
										fileOutputStream.write(buffer, 0, sent);
										fileOutputStream.flush();
									}

								}

							} else {
								System.out
										.println("File does not exist on server");
							}
						}
					}
				}
				inputFromServer.close();
				outputToServer.close();
			}

		} catch (IOException e) {
			System.err.println(e);
		}
	}
}